import React, { useState, useEffect, forwardRef } from 'react';
import { Input, Modal, Button, Tree, Select } from 'antd';
import { ExportOutlined } from '@ant-design/icons';
import { TextWidget, getMessage } from '@inbiz/react';
import { getImgCate } from '../../preview/web/services';
import { InbizIcon } from '@inbiz/utils';
import './cate.less';

const ImageCate: React.FC<Banner.IImagCateProps> = forwardRef((props, ref) => {
  const { value, onChange } = props;
  const [visible, setVisible] = useState(false);
  const [selectedRecord, setSelectRecord] =
    useState<Banner.imgCateRecord>(value);
  const [treeData, setTreeData] = useState<Banner.TreeDataSource[]>([
    {
      key: '0000-0000-0000',
      title: getMessage('banner.img'),
      children: [],
    },
  ]);
  const [searchOptions, setSearchOptions] = useState<Banner.ImgCateItem[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([
    '0000-0000-0000',
  ]);

  const toggleVisible = () => {
    setVisible(!visible);
  };

  const getCateList = async (
    callback: Function,
    pageSize: number,
    categoryName?: string,
  ) => {
    try {
      const res = await getImgCate({
        categoryName,
        pageSize,
      });
      callback(res);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    getCateList((res: any) => {
      setTreeData([
        {
          key: '0000-0000-0000',
          title: getMessage('banner.img'),
          children: (res?.CmsCategoryList || []).map(
            (i: Banner.ImgCateItem) => ({
              key: i.Key,
              title: i.Title,
            }),
          ),
        },
      ]);
    }, 99999);
  }, []);

  const handleSelect = (selectedKeys: any, e: any) => {
    const { selected, node } = e;

    if (!selected) {
      setSelectRecord(undefined as any);
    } else {
      setSelectRecord({
        key: node.key,
        title: node.title,
      });
    }
  };

  const handleOk = () => {
    onChange(selectedRecord);
    toggleVisible();
  };

  const handleSearch = (categoryName: string) => {
    getCateList(
      (res: any) => {
        setSearchOptions(res?.CmsCategoryList || []);
      },
      8,
      categoryName,
    );
  };

  const handleChange = (value: string, record: any) => {
    if (value) {
      setSelectRecord({
        key: value,
        title: record.children,
      });
      setExpandedKeys([...expandedKeys, value]);
    }
  };

  const handleExpand = (expandedKeys: any) => {
    setExpandedKeys(expandedKeys);
  };

  return (
    <div>
      <Input onClick={toggleVisible} value={selectedRecord?.title} readOnly />
      <Modal
        title={getMessage('banner.classificationSelect')}
        visible={visible}
        onOk={handleOk}
        onCancel={toggleVisible}
        okText={getMessage('global.sure')}
        cancelText={getMessage('global.cancel')}
      >
        <div className="cate-select-wrapper">
          <Select
            className="cate-select"
            showSearch
            onSearch={handleSearch}
            onChange={handleChange}
            notFoundContent={null}
            filterOption={false}
          >
            {searchOptions.map((i) => (
              <Select.Option key={i.Key}>{i.Title}</Select.Option>
            ))}
          </Select>
          <Button
            onClick={() =>
              window.open('/inbiz/admin#/content-manage/cms/imageManage')
            }
            className="edit-btn"
            type="primary"
            icon={<ExportOutlined />}
          >
            <TextWidget>banner.goEditing</TextWidget>
          </Button>
        </div>
        <Tree
          showIcon
          icon={<InbizIcon type="icon-shangchuan-hover" />}
          autoExpandParent
          treeData={treeData}
          expandedKeys={expandedKeys}
          selectedKeys={[selectedRecord?.key]}
          onSelect={handleSelect}
          onExpand={handleExpand}
        />
      </Modal>
    </div>
  );
});

export default ImageCate;
